class GroupsController < ApplicationController
  before_action :login_auth   
  def index
    @groups = Group.all
    if @groups.count == 0
      flash[:notice] = "please create a new group"
      redirect_to new_group_path
    end
  end

  def new
    @group = Group.new
  end

  def show
    @group = Group.find(params[:id])
    @users = @group.users
  end

  def edit
  end

  def create
    @group = Group.new(group_params)
    @group.owner_id = current_user.id
    if @group.save
      current_user.update_attribute(:group_id, @group.id)
      flash[:notice] = "create group #{@group.name} success"
    else
      flash[:notice] = "create group #{@group.name} failed"
    end
    redirect_to groups_path
  end

  def update
  end

  def destroy
  end
  def join
    if Group.find_by_id(params[:group_id]).lock_tag
      flash[:join] = 'the group already locked, can not join the group'
      @notice_msg =  'the group already locked, can not join the group'
    elsif current_user.group_id.to_s == params[:group_id]
      flash[:join] = "#{current_user.name} already joined the group"
      @notice_msg = 'already joined the group'
      # return
    else
      current_user.update(group_id: params[:group_id])
      flash[:join] = "#{current_user} joined group success"
      @notice_msg = 'join the group success, please refresh'
    end
    @members = current_group.users
    respond_to do |format|
      format.js {}
    end
  end
  def lock_group
    group = Group.find_by_id(params[:id])
    group.update_attributes(lock_tag: !group.lock_tag)
    redirect_to group_path(group)
  end
  private
  def group_params
    params.require(:group).permit(:name, :description)
  end
end
